package tech.aiflowy.system.controller;


import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.web.bind.annotation.*;
import tech.aiflowy.common.domain.Result;
import tech.aiflowy.common.entity.LoginAccount;
import tech.aiflowy.common.satoken.config.AdminSaTokenConfig;
import tech.aiflowy.common.satoken.config.SaConfigs;
import tech.aiflowy.common.satoken.util.SaTokenUtil;
import tech.aiflowy.common.web.controller.BaseCurdController;
import tech.aiflowy.log.annotation.LogRecord;
import tech.aiflowy.system.entity.SysToken;
import tech.aiflowy.system.service.SysTokenService;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.*;

/**
 * 系统配置表 控制层。
 *
 * @author michael
 * @since 2024-03-05
 */
@RestController("sysTokenController")
@RequestMapping("/api/v1/sysToken/")
public class SysTokenController  extends BaseCurdController<SysTokenService, SysToken> {

    public SysTokenController(SysTokenService service) {
        super(service);
    }

    @Override
 //   @SaCheckPermission("sysToken:list")
    public  Result page(HttpServletRequest request, String sortKey, String sortType, Long pageNumber, Long pageSize) {
        return super.page(request, sortKey, sortType, pageNumber, pageSize);
    }

    @Override
    @LogRecord("分页查询")
    protected Page<SysToken> queryPage(Page<SysToken> page, QueryWrapper queryWrapper) {
        return service.getMapper().paginateWithRelations(page, queryWrapper);
    }

    @Override
    protected Result onSaveOrUpdateBefore(SysToken entity, boolean isSave) {
        LoginAccount loginUser = SaTokenUtil.getLoginAccount();
        entity.setCreated(new Date());
        entity.setCreatedBy(loginUser.getId());
        entity.setTenantId(loginUser.getTenantId());
      
        if (isSave) {
            StpLogic logic  = new StpLogic(StpUtil.TYPE);
            SaTokenConfig config = SaConfigs.defaultConfig();
            config.setTokenName(AdminSaTokenConfig.LOGIN_TYPE + "-token");
            config.setIsConcurrent(true);
            config.setMaxLoginCount(3);
            config.setTimeout(-1);
            config.setTokenStyle("simple-uuid");
            logic.setConfig(config);
            String token = logic.getTokenValue();
            entity.setTokenValue(token);

        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(SysToken::getTokenValue, entity.getTokenValue());
        boolean flag=service.exists(wrapper);
        if(flag){
            return Result.fail();
        }
        return null;
    }

}